package com.gecba.system.config.swagger;

import com.gecba.system.config.properties.SwaggerProperties;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import static springfox.documentation.builders.PathSelectors.regex;

/**
 * @author ChenBo
 * @className Swagger2Config
 * @date 2021/7/19
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({SwaggerProperties.class})
@EnableSwagger2WebMvc
public class Swagger2Config {

    @Autowired
    private SwaggerProperties properties;

    @Bean
   public Docket createRestApi(){
       return new Docket(DocumentationType.SWAGGER_2)
               .groupName(properties.getGroup())
               .apiInfo(apiInfo()).select()
               // 扫描所有有注解的api，用这种方式更灵活
               .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
               .paths(regex(".*/gecba/.*").negate())
               .build();

   }

   @Bean
    public Docket createAppRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(properties.getGroup2())
                .apiInfo(apiInfo()).select()
                // 扫描所有有注解的api，用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(regex(".*/gecba/.*"))
                .build();
    }


   private ApiInfo apiInfo(){
       return new ApiInfoBuilder()
               .title(properties.getTitle())
               .description(properties.getDescription())
               .termsOfServiceUrl(properties.getTermsOfServiceUrl())
               .contact(contact())
               .version(properties.getVersion())
               .build();
   }

   private Contact contact(){
       return new Contact(
               properties.getContact().getName(),
               properties.getContact().getUrl(),
               properties.getContact().getEmail()
       );
   }
}
